<?php
/**
 * topapi
 *
 * -- common.map
 * -- 用于获取送货点
 *
 * @author 何永真
 * @time 2018.5.31 13:42
 */
class topapi_api_v1_common_map implements topapi_interface_api{

    /**
     * 接口作用说明
     */
    public $apiDescription = '用于获取送货点';

    /**
     * 定义API传入的应用级参数
     * @desc 用于在调用接口前，根据定义的参数，过滤必填参数是否已经参入，并且定义参数的数据类型，参数是否必填，参数的描述
     * @return array 返回传入参数
     */
    public function setParams()
    {
        return [
            'address' => ['type'=>'string', 'valid'=>'required', 'desc'=>'收货地址'],
        ];

        return $return;
    }

    /**
     * 用于获取送货点
     * @param  array $params         入参
     * @return array depot           送货点数据
     * @return Sting code            返回状态码(0表示是，99表示否)
     * @return Sting info            是否支持送货上门
     */
    public function handle($params)
    {
        $address = $params['address'];
        // $address = '湖北省襄阳市襄州区政府';

        // @error_log('=======p======'.print_r($address,true).print_r($is_save,true).chr(10),3,'/data/httpd/b2b2c/map_log.txt'); 

        // file_put_contents();

        $Url="http://api.map.baidu.com/geocoder/v2/?address=".$address."&output=json&ak=CAd14de4d13fa18ebecbd5ab92af71bc";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $Url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果把这行注释掉的话，就会直接输出
        $result=curl_exec($ch);
        curl_close($ch);
        $infolist=json_decode($result);

        // @error_log('=======p======'.dump($infolist,true).dump($is_save,true).chr(10),3,'/data/httpd/b2b2c/map_log.txt'); 

        // echo $infolist;

        $return=array();
        if(isset($infolist->result->location) && !empty($infolist->result->location)){
            $return=array(
                'lng'=>$infolist->result->location->lng,
                'lat'=>$infolist->result->location->lat,
            );
            // @error_log('=======p======'.dump($arr,true).chr(10),3,'/data/httpd/b2b2c/map_log.txt'); 
        }else{
            return false;
        }
        // dump($return);

        $deliveryModel = app::get('syslogistics')->model('delivery_point');
        $deliveryData = $deliveryModel->getList('id,depot_bn,depot_name,longitude,latitude');

        // dump($deliveryData);

        foreach ($deliveryData as $key => $value) {

            $distance[$key]['id'] = $value['id'];
            $distance[$key]['depot_bn'] = $value['depot_bn'];
            $distance[$key]['depot_name'] = $value['depot_name'];
            //计算距离
            $distance[$key]['distance'] = $this->getDistance($value['longitude'],$value['latitude'],$return['lng'],$return['lat']);
            
            $tmp[$key] = $distance[$key]['distance']; 
            array_multisort($tmp,SORT_ASC,$distance);

        }
        
        foreach ($distance as $key => $value) {
            if ($value['distance']>2) {
                unset($distance[$key]);
            }
        }
        // $distance = array_values($distance);
        // dump($distance);

        //根据2公里范围内的送货点（仓库）的仓库编码和订单商品ID，查询仓库商品库存是否满足订单商品数量，筛选出2公里范围内的库存足够的送货点

        //如果出现多个2公里范围内的库存足够的送货点，那么取最近的送货点
        // dump($distance[0]);

        if ($distance) {
            $returns['depot'][] = $distance[0];
            $returns['code'] = 0;
            $returns['info'] = '支持送货上门';
        } else {
            $returns['depot'] = '';
            $returns['code'] = 99;
            $returns['info'] = '不支持送货上门';
        }
        
        // dump($returns);
        // echo '距离目的地：'.$distance.'km';

        return $returns;
    }

    /**
     * 计算两组经纬度坐标之间的距离
     * @param $lat1 纬度1
     * @param $lng1 经度1
     * @param $lat2 纬度2
     * @param $lng2 经度2
     * @param int $len_type 返回值类型(1-m 2-km)
     * @param int $decimal 保留小数位数
     * @return float
     */
    function getDistance($lat1, $lng1, $lat2, $lng2, $len_type = 2, $decimal = 2)
    {
        $radLat1 = $lat1 * 3.1415926 / 180.0;
        $radLat2 = $lat2 * 3.1415926 / 180.0;
        $a = $radLat1 - $radLat2;
        $b = ($lng1 * 3.1415926 / 180.0) - ($lng2 * 3.1415926 / 180.0);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = $s * 6378.137;
        $s = round($s * 1000);
        if ($len_type > 1) {
            $s /= 1000;
        }
        return round($s, $decimal);
    }

    /**
     * 返回json格式的例子
     * @return string 结果json串
     */
    public function returnJson()
    {
        return '{"errorcode":0,"msg":"","data":{"depot":[{"id":4,"depot_bn":"04","depot_name":"襄阳剧院","distance":1.76}],"code":0,"info":"支持送货上门"}}';
    }

}

